<template>
  <el-dialog :title="title" v-loading="loading" :visible.sync="visible" @close="handleCancel" :append-to-body="true"
    :width="title == '做账记录'?'1400px':(title == '操作记录'?'1200px':'400px')">
    <div class="handle-box" v-if="title == '分配会计'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 8px;">选择做账会计：</div>
        <xh-user-cell class="handle-item-content" :radio="true" placeholder="点击选择（单选）" @value-change="accountancyChage"
          infoType="1">
        </xh-user-cell>
      </flexbox>
    </div>
    <div class="handle-box" v-if="title == '分配会计'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 8px;">选择咨询会计：</div>
        <xh-user-cell class="handle-item-content" :radio="true" placeholder="点击选择（单选）" @value-change="consultChage"
          infoType="2">
        </xh-user-cell>
      </flexbox>
    </div>
    <div class="handle-box" v-if="title == '开始服务'">
      <flexbox class="handle-item" align="stretch">
        <!-- 服务开始时间： -->
        <div class="handle-item-name" style="margin-top: 8px;">服务开始时间：</div>
        <div class="select-group">
          <el-date-picker v-model="accounting_start_time" type="date" :value-format="'yyyy-MM-dd HH:mm:ss'"
            placeholder="选择日期">
          </el-date-picker>
        </div>
      </flexbox>
    </div>
    <div class="handle-box" v-if="title == '会计经理'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 8px;">选择会计经理：</div>
        <xh-user-cell class="handle-item-content" :radio="true" placeholder="点击选择（单选）" @value-change="ChangeLeader"
          infoType="4" ref="leaderRef" :infoParams="{ group_id: 33 }">
        </xh-user-cell>
      </flexbox>
    </div>
    <div class="handle-box" v-if="title == '分配外勤'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 8px;">选择外勤人员：</div>
        <xh-user-cell class="handle-item-content" :radio="true" placeholder="点击选择（单选）" @value-change="outsideChage"
          ref="del" infoType="3">
        </xh-user-cell>
      </flexbox>
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 10px;">办理事项：</div>
        <el-select v-model="matter" placeholder="请选择办理事项" filterable style="margin-top: 4px; width: 100%;" @change="changeMatter">
            <el-option v-for="item in matterList" :key="item.id" :label="item.matter" :value="item.id" />
        </el-select>
      </flexbox>
      <flexbox v-if="matter" class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 10px;">提成金额：</div>
        <div style="margin-top: 10px;"> {{ matter_price }} </div>
      </flexbox>
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 10px;">备注：</div>
        <el-input v-model="remark" style="margin-top: 4px;" type="textarea" clearable placeholder="请填写备注" />
      </flexbox>
      <flexbox v-if="assignmentList.length > 0" class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 10px;">分配记录：</div>
        <div style="flex: 1; max-height: 200px; overflow-y: auto;">
          <el-timeline>
            <el-timeline-item
              v-for="(item, index) in assignmentList"
              :key="index"
              color="#0bbd87"
              placement="top"
              :timestamp="item.realname"
            >
              <div>
                <div style="margin-bottom: 10px;"> {{ item.title }} </div>
                <div> {{item.allocate_time}} </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </flexbox>
    </div>



    <div class="handle-box" v-if="title == '做账'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 8px;">请选择做账时间：</div>
        <div class="select-group">
          <el-date-picker v-model="accountingDate" type="month" :value-format="'yyyy-MM'" placeholder="选择日期">
          </el-date-picker>
        </div>
      </flexbox>
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 10px;">填写备注：</div>
        <el-input v-model="memo" style="margin-top: 4px;" type="textarea" clearable placeholder="请填写备注"></el-input>
      </flexbox>
    </div>
    <div class="handle-box" v-if="title == '跟进记录'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 10px;">填写备注：</div>
        <el-input v-model="recordMes" style="margin-top: 4px;" type="textarea" clearable placeholder="请填写备注"></el-input>
      </flexbox>
    </div>
    <div class="handle-box" v-if="title == '工本费'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 16px;">工本费：</div>
        <el-select v-model="cost_production" placeholder="请选择工本费" style="margin-top: 10px;">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- <el-input-number v-model="cost_production" style="margin-top: 12px;" :precision="2" clearable
          placeholder="请输入工本费"></el-input-number> -->
      </flexbox>
    </div>

    <div class="handle-box" v-if="title == '填写提成'">
      <flexbox class="handle-item" align="stretch">
        <div class="handle-item-name" style="margin-top: 16px;">请填写提成金额：</div>
        <el-input-number v-model="money" style="margin-top: 12px;" :precision="2" clearable placeholder="请输入金额">
        </el-input-number>
      </flexbox>
    </div>

    <div class="handle-box" v-if="title == '做账记录'">
      <flexbox class="handle-item" align="stretch">
        <el-table v-loading="loading" :data="orderList">
          <el-table-column label="审核人" align="center" prop="admin_realname" />
          <el-table-column label="做账会计" align="center" prop="accountancy_user_realname" />
          <el-table-column label="年" align="center" prop="year" width="100" />
          <el-table-column label="月" align="center" prop="month" width="100" />
          <el-table-column label="创建时间" align="center" width="180" prop="createtime" />
          <el-table-column label="备注" align="center" show-overflow-tooltip prop="memo" width="200" />
          <el-table-column label="审核时间" align="center" width="180" prop="examine_time" />
          <el-table-column label="审核备注" align="center" show-overflow-tooltip prop="remark" width="200" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.status == 0 ">{{'待审核' }}</el-tag>
              <el-tag type="info" v-if="scope.row.status == 1">{{ '已通过' }}</el-tag>
              <el-tag type="danger" v-if="scope.row.status == 2 ">{{'已驳回' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="120">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.status == 0 &&examineAcc" style="cursor: pointer;"
                @click="toPass(scope.row.accounting_id)">
                {{ '通过'}}
              </el-tag>
              <el-tag type="danger" v-if="scope.row.status == 0&&examineAcc" style="cursor: pointer;"
                @click="toReject(scope.row.accounting_id)">
                {{ '驳回'}}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </flexbox>
    </div>

    <div class="handle-box" v-if="title == '操作记录'">
      <flexbox class="handle-item" align="stretch">
        <el-table v-loading="loading" :data="orderList">
          <el-table-column label="操作时间" align="center" width="150" prop="createtime" />
          <el-table-column label="备注" align="center" show-overflow-tooltip prop="remark" width="300" />
          <el-table-column label="类型" align="center" width="150">
            <template slot-scope="scope">
              <el-tag type="info" v-if="scope.row.status == 0">{{ '接收' }}</el-tag>
              <el-tag type="danger" v-if="scope.row.status == 1 ">{{'完结' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="120">
            <template slot-scope="scope">
              <el-tag type="info" v-if="scope.row.state == 0">{{ '待审核'}}</el-tag>
              <el-tag type="success" v-if="scope.row.state == 1">{{ '已通过' }}</el-tag>
              <el-tag type="danger" v-if="scope.row.state == 2 ">{{'已驳回' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="170">
            <template slot-scope="scope">
              <el-tag type="success" v-if="scope.row.state == 0 &&examinePer" style="cursor: pointer;"
                @click="getPass(scope.row.assignfield_recorde_id)">
                {{ '通过'}}
              </el-tag>
              <el-tag type="danger" v-if="scope.row.state == 0&&examinePer" style="cursor: pointer;"
                @click="getReject(scope.row.assignfield_recorde_id)">
                {{ '驳回'}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="驳回原因" align="center" prop="memo" width="300" />
        </el-table>
      </flexbox>
    </div>

    <span slot="footer" class="dialog-footer" v-if="title != '做账记录'&&title != '操作记录'">
      <el-button @click.native="handleCancel">取消</el-button>
      <el-button type="primary" @click.native="handleConfirm">保存</el-button>
    </span>
  </el-dialog>

</template>

<script>
  import {
    XhUserCell
  } from '@/components/CreateCom'
  import {
    allocation,
    startService,
    assignfieldAssign,
    accountingExamine,
    personnelExamine,
    adminIndexAuthList,
    personnelAddflow,
    personnelAllocationRecord
  } from '@/api/common'
  import {
    accountingCost,
    personnelCommission,
    accountingMake,
    accountingMakelist,
    upAccountingUser
  } from '@/api/customermanagement/common'
  import { getMatterPage } from "@/api/systemManagement/matter";
  export default {
    /** 客户管理 的 勾选后的 团队成员 操作 移除操作不可移除客户负责人*/
    name: 'teams-handle',
    components: {
      XhUserCell
    },
    mixins: [],
    watch: {
      dialogVisible: {
        handler(val) {
          this.visible = val
          if (val) {
            this.money = '',
              this.memo = '',
              this.remark = '',
              this.recordMes = ''
            if (this.title == '分配外勤') {
              this.matter = '';
              this.matter_price = 0;
              this.getMatterList();
              this.getAssignmentList();
            }
          }
        },
        deep: true,
        immediate: true
      }
    },
    props: {
      dialogVisible: {
        type: Boolean,
        required: true,
        default: false
      },
      title: {
        type: String,
        default: ''
      },
      /** 没有值就是全部类型 有值就是当个类型 */
      crmType: {
        type: String,
        default: ''
      },
      contractId: {
        type: String,
        default: ''
      },
      /** 转移数据 */
      selectionList: {
        type: Array,
        default: () => {
          return []
        }
      },
      /** 转移数据 */
      orderList: {
        type: Array,
        default: () => {
          return []
        }
      }
    },
    data() {
      return {
        recordMes: '',
        remark: '',
        matter: '',
        matter_price: 0,
        matterList: [],
        value1: '',
        loading: false, // 加载动画
        visible: false,
        usersList: [], // 变更负责人
        handleType: 1, // 操作类型
        addsTypes: [], // 添加至
        accountancy_user_id: '',
        consult_user_id: '',
        accounting_start_time: '',
        cost_production: '',
        accountingDate: '',
        memo: '',
        user_id: [],
        money: '',
        examineAcc: false,
        examinePer: false,
        assignmentList: [], // 分配记录列表
        accounting_user_id: '', // 会计经理ID
        options: [
          { label: 200, value: 200 },
          { label: 0, value: 0 }
        ]
      }
    },
    created() {
      this.getAuth()
    },
    computed: {},
    mounted() {
      this.accountingDate = ''
      this.visible = this.dialogVisible
    },
    methods: {
      // 获取权限
      getAuth() {
        return new Promise((resolve, reject) => {
          adminIndexAuthList().then((response) => {
            const data = response.data
            this.examineAcc = data.crm.accounting ? data.crm.accounting.examine : false
            this.examinePer = data.crm.personnel ? data.crm.personnel.examine : false
            resolve(response)
          }).catch(error => {
            reject(error)
          })
        })
      },
      getReject(id) {
        this.$prompt('请输入理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({
          value
        }) => {
          this.loading = true
          personnelExamine({
              state: 2,
              memo: value,
              assignfield_recorde_id: id
            })
            .then(res => {
              if (res.code == 200) {
                this.$message.success(res.data)
                this.$parent.handleDivided(this.contractId, '操作记录')
                // this.getList()
                this.loading = false
              }

            })
            .catch(() => {
              this.loading = false
            })
        }).catch(() => {});
      },
      toReject(id) {
        this.$prompt('请输入理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({
          value
        }) => {
          this.loading = true
          accountingExamine({
              status: 2,
              contract_id: this.contractId,
              remark: value,
              accounting_id: id
            })
            .then(res => {
              if (res.code == 200) {
                this.$message.success(res.data)
                this.getList()
                this.loading = false
              }

            })
            .catch(() => {
              this.loading = false
            })
        }).catch(() => {});
      },
      getPass(id) {
        this.$prompt('请输入理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({
          value
        }) => {
          this.loading = true
          personnelExamine({
              state: 1,
              assignfield_recorde_id: id,
              memo: value,
            })
            .then(res => {
              if (res.code == 200) {
                this.$message.success(res.data)
                // this.getList()
                this.$parent.handleDivided(this.contractId, '操作记录')
                this.loading = false
              }

            })
            .catch(() => {
              this.loading = false
            })
        }).catch(() => {});
      },
      toPass(id) {
        this.$prompt('请输入理由', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({
          value
        }) => {
          this.loading = true
          accountingExamine({
              status: 1,
              contract_id: this.contractId,
              remark: value,
              accounting_id: id
            })
            .then(res => {
              if (res.code == 200) {
                this.$message.success(res.data)
                this.getList()
                this.loading = false
              }

            })
            .catch(() => {
              this.loading = false
            })
        }).catch(() => {});
      },
      getList() {
        this.loading = true
        accountingMakelist({
            contract_id: this.contractId,
          })
          .then(res => {
            this.orderList = res.data.list
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      },
      // 获取分配记录列表
      getAssignmentList() {
        personnelAllocationRecord({
          contract_id: this.contractId,
        }).then((res) => {
          this.assignmentList = res.data || [];
        })
      },
      // 获取办件事项列表
      getMatterList() {
        getMatterPage({
            page: 1,
            limit: 9999,
          })
          .then((res) => {
            this.matterList = res.data.list;
          })
      },
      // 选择办理事项
      changeMatter(val) {
        let row = this.matterList.find((item) => item.id == val);
        this.matter_price = row.money || 0;
      },
      /**
       * 取消选择
       */
      handleCancel() {
        this.visible = false
        this.assignmentList = []
        if (this.$refs.leaderRef) {
          this.$refs.leaderRef.clearData()
        }
        this.$emit('update:dialogVisible', false)
      },
      /** 负责人更改 */
      consultChage(data) {
        this.consult_user_id = data.value[0].id
      },
      /** 负责人更改 */
      outsideChage(data) {
        if (data.value.length > 0) {
          let arr = data.value.map((item, index) => {
            return {
              id: item.id,
              value: index
            }
          })
          arr = this.arrToObj(arr)
          for (let i in arr) {
            this.user_id[i] = arr[i]
          }
        } else {
          this.user_id = []
        }
        console.log(this.user_id, 'this.user_id')
      },
      arrToObj(arr) {
        let obj = {}
        arr.forEach(item => {
          obj[item.value] = item.id
        })
        return obj
      },
      /** 负责人更改 */
      accountancyChage(data) {
        this.accountancy_user_id = data.value[0].id
      },
      // 会计经理更改
      ChangeLeader(data) {
        this.accounting_user_id = data.value[0].id
      },
      handleConfirm() {
        if (this.title == '分配会计') {
          if (this.accountancy_user_id == '') {
            this.$message.error('请选择做账会计')
          } else if (this.consult_user_id == '') {
            this.$message.error('请选择咨询会计')
          } else {
            this.loading = true
            allocation({
                contract_id: this.contractId,
                accountancy_user_id: this.accountancy_user_id,
                consult_user_id: this.consult_user_id,
                accounting_start_time: this.accounting_start_time
              })
              .then(res => {
                this.$message.success(res.data)
                this.accountancy_user_id = ''
                this.consult_user_id = ''
                this.accounting_start_time = ''
                this.loading = false
                this.handleCancel()
              })
              .catch(() => {
                this.loading = false
              })
          }
        } else if (this.title == '开始服务') {
          if (this.accounting_start_time == '') {
            this.$message.error('请选择服务开始时间')
            return
          }
          this.loading = true
          startService({
              contract_id: this.contractId,
              accounting_start_time: this.accounting_start_time
            })
            .then(res => {
              this.$message.success(res.data)
              this.accounting_start_time = ''
              this.loading = false
              this.handleCancel()
            })
            .catch(() => {
              this.loading = false
            })
        } else if (this.title == '会计经理') {
          console.log('')
          this.loading = true
          upAccountingUser({
            accounting_id: this.accounting_user_id,
            contract_id: this.contractId,
          }).then(res => {
              this.$message.success(res.data)
              this.accounting_user_id = ''
              this.loading = false
              this.handleCancel()
              this.$emit("complete")
            })
            .catch(() => {
              this.loading = false
            })
        } else if (this.title == '工本费') {
          this.loading = true
          accountingCost({
              cost_production: this.cost_production,
              contract_id: this.contractId
            })
            .then(res => {
              this.$message.success(res.data)
              this.cost_production = ''
              this.loading = false
              this.handleCancel()
            })
            .catch(() => {
              this.loading = false
            })
        } else if (this.title == '填写提成') {
          this.loading = true
          personnelCommission({
              money: this.money,
              assignfield_id: this.contractId
            })
            .then(res => {
              this.$message.success(res.data)
              this.money = ''
              this.loading = false
              this.handleCancel()
            })
            .catch(() => {
              this.loading = false
            })
        } else if (this.title == '跟进记录') {
          if (this.recordMes == '') {
            this.$message.error('请填写备注')
          } else {
            this.loading = true
            personnelAddflow({
                assignfield_id: this.contractId,
                remark: this.recordMes,
              })
              .then(res => {
                this.$message.success(res.data)
                this.recordMes = ''
                this.loading = false
                this.handleCancel()
              })
              .catch(() => {
                this.loading = false
              })
          }
        } else if (this.title == '分配外勤') {
          if (this.user_id.length == '') {
            this.$message.error('请选择外勤人员')
          } else if (this.matter == '') {
            this.$message.error('请选择办理事项')
          } else {
            let row = this.matterList.find(i => i.id == this.matter);
            let data = {
              contract_id: this.contractId,
              user_id: this.user_id,
              name: row.matter,
              money: this.matter_price,
              remark: this.remark,
            }
            this.loading = true
            assignfieldAssign(data)
              .then(res => {
                this.$message.success(res.data)
                this.$refs.del.deleteuser(0)
                this.user_id = []
                this.matter = ''
                this.matter_price = 0;
                this.remark = ''
                this.loading = false
                this.handleCancel()
              })
              .catch(() => {
                this.loading = false
              })
          }
        } else {
          if (this.accountingDate == '') {
            this.$message.error('请选择做账日期')
          } else {
            this.loading = true
            accountingMake({
                year: this.accountingDate.split('-')[0],
                month: this.accountingDate.split('-')[1],
                memo: this.memo,
                contract_id: this.contractId
              })
              .then(res => {
                this.$message.success(res.data)
                this.accountingDate = ''
                this.memo = ''
                this.loading = false
                this.handleCancel()
              })
              .catch(() => {
                this.loading = false
              })
          }

        }
      }
    }
  }

</script>

<style lang="scss" scoped>
  .tips {
    color: #777;
    font-size: 12px;
    position: absolute;
    bottom: -2px;
    right: 125px;
  }

  .handle-box {
    color: #333;
    font-size: 12px;
  }

  .handle-item {
    padding-bottom: 15px;
    position: relative;

    .handle-item-name {
      flex-shrink: 0;
      width: 140px;
      font-size: 14px;
    }

    .handle-item-content {
      flex: 1;
    }
  }

  .handle-bar {
    position: relative;
    margin-top: 10px;
    height: 30px;

    button {
      float: right;
      margin-right: 10px;
    }
  }

</style>
